package com.quick.develop.server;

import com.quick.develop.server.handle.QuickServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class QuickServer implements Runnable {

    private final int port;

    public QuickServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        new Thread(new QuickServer(8077)).start();
    }


    private void bind() {
        NioEventLoopGroup boos = new NioEventLoopGroup();
        NioEventLoopGroup works = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boos, works)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new QuickServerInitializer());
            ChannelFuture sync = serverBootstrap.bind(port).sync();
            sync.channel().closeFuture().sync();
        }catch (Exception e) {
           log.error("启动服务失败",e);
        } finally  {
            boos.shutdownGracefully();
            works.shutdownGracefully();
        }
    }

    @Override
    public void run() {
        this.bind();
    }
}
